package com.wn.rolectl.realm;

import com.wn.rolectl.entity.User;
import com.wn.rolectl.service.PermService;
import com.wn.rolectl.service.RolePermService;
import com.wn.rolectl.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Set;

/**
 * @program: projwe9
 * @description: shiro 验证realm
 * @author: Jason-Wei
 * @create: 2021-01-15 10:53
 **/
public class MyAuthRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Autowired
    RolePermService rolePermService;

    @Autowired
    PermService permService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取当前用户的所有权限
        String username = principalCollection.getPrimaryPrincipal().toString();
        User user = userService.findByUserType(username);
        List<Integer> pids = rolePermService.getAllPidByRid(user.getRole_id());
        Set<String> perms = permService.getAllUrlById(pids);
        // 将权限放入授权信息中
        SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
        s.setStringPermissions(perms);
        return s;

    }

    /**
     * @param authenticationToken
     * @Description:获取认证信息， 根据authenticationToken 中的信息查询数据库中对应用户信息并返回
     * @Author: jason-wei
     * @Date: 2021-01-15 10:57:51
     * @return: AuthenticationInfo
     **/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = authenticationToken.getPrincipal().toString();
        User user = userService.findByUserType(userName);
        if (ObjectUtils.isEmpty(user)) {
            throw new UnknownAccountException();
        }
        String password = user.getPassword();
        String salt = user.getSalt();
        return new SimpleAuthenticationInfo(userName, password, ByteSource.Util.bytes(salt), getName());
    }
}
